package com.skydoves.chatgpt.feature.chat.ddd.Channel4

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.core_database.database.AppDatabase
import com.example.core_database.entities.User
import com.skydoves.chatgpt.feature.chat.ddd.users.UserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import javax.inject.Inject


@HiltViewModel
class Channel4ViewModel @Inject constructor(
  application: Application,
  private val uidFlow: Flow<String>,
) : AndroidViewModel(application){
  private val userRepository: UserRepository

  private val _user = MutableLiveData<User?>()
  val user: LiveData<User?> = _user


  init {
    val userDao = AppDatabase.getDatabase(application).userDao()
    userRepository = UserRepository(userDao)
    loadUser()
  }

  private fun loadUser() {
    viewModelScope.launch {
      val userId = uidFlow.firstOrNull() ?: return@launch
      //找User
      val existingUser = userRepository.getUserById(userId)
      if (existingUser == null) {
        Log.i("AppUser","can't find${userId},create a new User")


      } else {
        Log.i("AppUser","find successfull: ${userId}")
        _user.postValue(existingUser)
      }
    }
  }

  fun updateUser(user: User){
    userRepository.updateUser(user)
  }


}